<template>
  <div class="add-address-container">
    <el-card class="add-address-card">
      <template #header>
        <div class="card-header">
          <h2>新增地址</h2>
          <el-button @click="goBack" type="default">
            <el-icon><ArrowLeft /></el-icon>返回
          </el-button>
        </div>
      </template>
      
      <el-form :model="addressForm" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="收件人姓名" prop="contactName">
          <el-input v-model="addressForm.contactName" placeholder="请输入收件人姓名" />
        </el-form-item>
        
        <el-form-item label="收件人电话" prop="contactPhone">
          <el-input v-model="addressForm.contactPhone" placeholder="请输入收件人电话" />
        </el-form-item>
        
        <el-form-item label="地址类型" prop="isDefault">
          <el-radio-group v-model="addressForm.isDefault">
            <el-radio :label="1">寄件地址</el-radio>
            <el-radio :label="0">收件地址</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="收件省市区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择省市区"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
            v-model="addressForm.detailAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">
            添加地址
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { userApi, type CreateAddressRequest } from '@/api/user'

// 定义地区选项的类型
interface RegionOption {
  value: string
  label: string
  children?: RegionOption[]
}

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const addressForm = reactive({
  contactName: '',
  contactPhone: '',
  isDefault: 0, // 默认为收件地址
  region: [] as string[],
  detailAddress: ''
})

// 表单验证规则
const rules: FormRules = {
  contactName: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  isDefault: [
    { required: true, message: '请选择地址类型', trigger: 'change' }
  ],
  region: [
    { required: true, message: '请选择省市区', trigger: 'change' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '详细地址长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

// 地区选项数据
const regionOptions = ref<RegionOption[]>([
  {
    value: 'beijing',
    label: '北京',
    children: [
      {
        value: 'beijing-city',
        label: '北京市',
        children: [
          { value: 'chaoyang', label: '朝阳区' },
          { value: 'haidian', label: '海淀区' },
          { value: 'dongcheng', label: '东城区' },
          { value: 'xicheng', label: '西城区' }
        ]
      }
    ]
  },
  {
    value: 'shanghai',
    label: '上海',
    children: [
      {
        value: 'shanghai-city',
        label: '上海市',
        children: [
          { value: 'huangpu', label: '黄浦区' },
          { value: 'xuhui', label: '徐汇区' },
          { value: 'changning', label: '长宁区' },
          { value: 'jingan', label: '静安区' }
        ]
      }
    ]
  },
  {
    value: 'guangdong',
    label: '广东',
    children: [
      {
        value: 'guangzhou',
        label: '广州市',
        children: [
          { value: 'tianhe', label: '天河区' },
          { value: 'yuexiu', label: '越秀区' },
          { value: 'haizhu', label: '海珠区' }
        ]
      },
      {
        value: 'shenzhen',
        label: '深圳市',
        children: [
          { value: 'futian', label: '福田区' },
          { value: 'nanshan', label: '南山区' },
          { value: 'luohu', label: '罗湖区' }
        ]
      }
    ]
  }
])

// 返回上一页
const goBack = () => {
  router.back()
}

// 组合完整地址
const getFullAddress = (): string => {
  const regionLabels = getRegionLabels(addressForm.region)
  return regionLabels.join('') + addressForm.detailAddress
}

// 获取地区标签
const getRegionLabels = (values: string[]): string[] => {
  const labels: string[] = []
  let currentOptions: RegionOption[] = regionOptions.value
  
  for (const value of values) {
    const option = currentOptions.find(opt => opt.value === value)
    if (option) {
      labels.push(option.label)
      currentOptions = option.children || []
    }
  }
  
  return labels
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 构建请求数据
    const requestData: CreateAddressRequest = {
      contactName: addressForm.contactName,
      contactPhone: addressForm.contactPhone,
      fullAddress: getFullAddress(),
      isDefault: addressForm.isDefault
    }
    
    // 调用API创建地址
    const response = await userApi.createAddress(requestData)
    
    if (response.code === 200 || response.code === 0) {
      ElMessage.success(response.message || '地址添加成功！')
      router.push('/addressbook')
    } else {
      ElMessage.error(response.message || '地址添加失败')
    }
    
  } catch (error: any) {
    console.error('创建地址失败:', error)
    ElMessage.error(error.message || '地址添加失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}
</script>

<style scoped>
.add-address-container {
  padding: 20px;
}

.add-address-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.el-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>